package com.itboye.hutouben;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.hutouben.activity.RecyclerViewTest;
import com.itboye.hutouben.activity.login.LoginActivity;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.base.MyApplcation;
import com.itboye.hutouben.bean.ConfigAppBean;
import com.itboye.hutouben.fragment.IndexFragment;
import com.itboye.hutouben.fragment.LunTanFragment;
import com.itboye.hutouben.fragment.MeFragment;
import com.itboye.hutouben.fragment.DaoLuFragment;
import com.itboye.hutouben.fragment.StoreFragment;
import com.itboye.hutouben.logincontroller.LoginController;
import com.itboye.hutouben.logincontroller.LoginedState;
import com.itboye.hutouben.logincontroller.UnLoginState;
import com.itboye.hutouben.presenter.UserPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.util.UpdateManager;
import com.itboye.hutouben.volley.ResultEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.umeng.message.common.UmengMessageDeviceConfig.getAppVersionName;

public class MainActivity extends BaseActivity implements Observer {

    Button btn_login;
    EditText et_username, et_userpwd;
    View me_layout, index_layout, message_layout, store_layout, luntan_layout2;
    private FragmentManager fragmentManager;
    private IndexFragment indexFragment;
    private StoreFragment storeFragment;
    private DaoLuFragment messageFragment;
    private MeFragment meFragment;
    private LunTanFragment lunTanFragment;
    public static MainActivity act;

    UserPresenter userPresenter;
    private long touchTime = 0;
    private long waitTime = 2000;


    public static MainActivity onSetFragment() {
        return act;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStatusBarColor(R.color.white);
        userPresenter = new UserPresenter(this);
        userPresenter.getConfigApp();
        initView();
        act = this;
        fragmentManager = getSupportFragmentManager();
        // 第一次启动时选中第0个tab
        setTabSelection(0);
    }


    @Override
    protected void onInit() {

    }


    private void initView() {
        message_layout = findViewById(R.id.message_layout);
        store_layout = findViewById(R.id.store_layout);
        index_layout = findViewById(R.id.index_layout);
        me_layout = findViewById(R.id.me_layout);
        luntan_layout2 = findViewById(R.id.luntan_layout2);
//        message_image = (ImageView) findViewById(message_image);
//        index_image = (ImageView) findViewById(index_image);
//        store_image = (ImageView) findViewById(store_image);
//        me_image = (ImageView) findViewById(me_image);
//        message_text = (TextView) findViewById(message_text);
//        index_text = (TextView) findViewById(index_text);
//        store_text = (TextView) findViewById(store_text);
//        me_text = (TextView) findViewById(me_text);
        message_layout.setOnClickListener(this);
        index_layout.setOnClickListener(this);
        store_layout.setOnClickListener(this);
        me_layout.setOnClickListener(this);
        luntan_layout2.setOnClickListener(this);

        /**
         * 登录状态
         */
        if ((Boolean) SPUtils.get(MyApplcation.ctx, null,
                Const.IS_LOGINED, false)) {
            LoginController.setLoginState(new LoginedState());
            Log.v("logined", "已经登录");
        } else {
            LoginController.setLoginState(new UnLoginState());
            Log.v("logined", "未登录");
        }
    }

    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.btn_login:
//                String userName = et_username.getText().toString();
//                if (userName.equals("")) {
//                    ByAlert.alert("请输入用户名");
//                }
//                String userPwd = et_userpwd.getText().toString();
//                if (userPwd.equals("")) {
//                    ByAlert.alert("请输入密码");
//                }
//                userPresenter.login(userName, userPwd);
//                break;

            case R.id.index_layout:
                // 当点击了消息tab时，选中第1个tab
                setTabSelection(0);
                break;
            case R.id.store_layout:
                setTabSelection(1);
                break;
            case R.id.message_layout:
                setTabSelection(2);
                break;
            case R.id.luntan_layout2:
                setTabSelection(3);
                break;
            case R.id.me_layout:
                setTabSelection(4);
                break;
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    @SuppressLint("ResourceAsColor")
    public void setTabSelection(int index) {
        // 每次选中之前先清楚掉上次的选中状态
        clearSelection();
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                // 当点击了首页tab时，改变控件的图片和文字颜色
                setStatusBarColor(R.color.main_color_two);
                ((ImageView) findViewById(R.id.index_image)).setImageResource(R.drawable.shouye_selected);
                ((TextView) findViewById(R.id.index_text))
                        .setTextColor(getResources().getColor(R.color.blue));
                if (indexFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    indexFragment = new IndexFragment();
                    transaction.add(R.id.content, indexFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(indexFragment);
                }
                break;
            case 1:
                setStatusBarColor(R.color.main_color_two);
                // 当点击了消息tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.store_image)).setImageResource(R.drawable.shangcheng_selected);
                ((TextView) findViewById(R.id.store_text)).setTextColor(getResources().getColor(R.color.blue));
                if (storeFragment == null) {
                    // 如果ContactsFragment为空，则创建一个并添加到界面上
                    storeFragment = new StoreFragment();
                    transaction.add(R.id.content, storeFragment);
                } else {
                    // 如果ContactsFragment不为空，则直接将它显示出来
                    transaction.show(storeFragment);
                }
                break;
            case 2:
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent1);
                    return;
                }
                setStatusBarColor(R.color.main_color_two);
                // 当点击了我的tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.message_image)).setImageResource(R.drawable.jiuyuan_selected);
                ((TextView) findViewById(R.id.message_text)).setTextColor(getResources().getColor(R.color.blue));

                if (messageFragment == null) {
                    // 如果SettingFragment为空，则创建一个并添加到界面上
                    messageFragment = new DaoLuFragment();
                    transaction.add(R.id.content, messageFragment);
                } else {
                    // 如果SettingFragment不为空，则直接将它显示出来
                    transaction.show(messageFragment);
                }
                break;
            case 3:
                setStatusBarColor(R.color.main_color_two);
                // 当点击了服务tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.luntan_image)).setImageResource(R.drawable.luntan_selected);
                ((TextView) findViewById(R.id.luntan_text)).setTextColor(getResources().getColor(R.color.blue));
                if (lunTanFragment == null) {
                    // 如果LunTanFragment为空，则创建一个并添加到界面上
                    lunTanFragment = new LunTanFragment();
                    transaction.add(R.id.content, lunTanFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(lunTanFragment);
                }

                break;

            case 4:
                setStatusBarColor(R.color.main_color_two);
                // 当点击了服务tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.me_image)).setImageResource(R.drawable.geren_selected);
                ((TextView) findViewById(R.id.me_text)).setTextColor(getResources().getColor(R.color.blue));
                if (meFragment == null) {
                    // 如果NewsFragment为空，则创建一个并添加到界面上
                    meFragment = new MeFragment();
                    transaction.add(R.id.content, meFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(meFragment);
                }

                break;

            default:

                break;
        }
        transaction.commit();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    /**
     * 清除掉所有的选中状态。
     */

    private void clearSelection() {
        ((ImageView) findViewById(R.id.message_image)).setImageResource(R.drawable.jiuyuan);
        ((TextView) findViewById(R.id.message_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.index_image)).setImageResource(R.drawable.shouye);
        ((TextView) findViewById(R.id.index_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.store_image)).setImageResource(R.drawable.shangcheng);
        ((TextView) findViewById(R.id.store_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.me_image)).setImageResource(R.drawable.geren);
        ((TextView) findViewById(R.id.me_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.luntan_image)).setImageResource(R.drawable.luntan);
        ((TextView) findViewById(R.id.luntan_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));

    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (indexFragment != null) {
            transaction.hide(indexFragment);
        }
        if (storeFragment != null) {
            transaction.hide(storeFragment);
        }
        if (messageFragment != null) {
            transaction.hide(messageFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }
        if (lunTanFragment != null) {
            transaction.hide(lunTanFragment);
        }

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.config_success) {
                ConfigAppBean appUpdateBean = (ConfigAppBean) entity.getData();
                String jgVersion = appUpdateBean.getJgVersion();
                int versionInt = Integer.parseInt(jgVersion.replace(".", ""));
                String oldVersion = getAppVersionName(MainActivity.this);
                int versionoldInt = Integer.parseInt(oldVersion.replace(".", ""));

                if (versionoldInt < versionInt) {
                    onManager(appUpdateBean);
                } else {
                }

                List<ConfigAppBean.A> bean = new ArrayList<ConfigAppBean.A>();
                bean.add(appUpdateBean.getShopIcons());

                SPUtils.put(this, null,
                        Const.JiaoBiao, bean.get(0).getJiaobiao());

                List<ConfigAppBean.Phone> beans = new ArrayList<ConfigAppBean.Phone>();
                beans.add(appUpdateBean.getCustomerPhone());
                SPUtils.put(this, null,
                        Const.TEL, beans.get(0).getTel());
            } else if (entity.getEventType() == UserPresenter.config_fail) {
                ByAlert.alert("更新解析失败");
            }
            if (entity.getEventType() == UserPresenter.login_success) {
                ByAlert.alert(entity.getData());
                Intent intent = new Intent(MyApplcation.ctx, RecyclerViewTest.class);
                startActivity(intent);
            } else if (entity.getEventType() == UserPresenter.login_fail) {
                ByAlert.alert(entity.getData());
            }
        }
    }

    public void onManager(ConfigAppBean appUpdateBean) {
        UpdateManager manager = new UpdateManager(this,
                appUpdateBean.getUpdateLog() + "",
                appUpdateBean.getDownLoadUrl(), appUpdateBean.getVersion());
        manager.checkUpdateInfo();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                ByAlert.alert("再按一次退出");
                touchTime = currentTime;
            } else {
                finish();
                //退出后关闭进程
                //   android.os.Process.killProcess(android.os.Process.myPid());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
